var vue;
var layedit;
var editIndexTie;
var editIndexFloor;
var layer;

function buildTieEditor() {
    editIndexTie = layedit.build('tie-content', {
        tool: [
            'strong' //加粗
            , 'italic' //斜体
            , 'underline' //下划线
            , 'del' //删除线
            , '|' //分割线
            , 'left' //左对齐
            , 'center' //居中对齐
            , 'right' //右对齐
            , 'link' //超链接
            , 'unlink' //清除链接
            , 'face' //表情
        ]
    });
}

function buildFloorEditor() {
    editIndexFloor = layedit.build('floor-content', {
        tool: [
            'strong' //加粗
            , 'italic' //斜体
            , 'underline' //下划线
            , 'del' //删除线
            , '|' //分割线
            , 'left' //左对齐
            , 'center' //居中对齐
            , 'right' //右对齐
            , 'link' //超链接
            , 'unlink' //清除链接
            , 'face' //表情
        ]
    });
}

function formatDate(date, fmt) {
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    var o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
    };
    for (var k in o) {
        if (new RegExp('(' + k + ')').test(fmt)) {
            var str = o[k] + '';
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str));
        }
    }
    return fmt;
};

function padLeftZero(str) {
    return ('00' + str).substr(str.length);
}

$(document).ready(function () {
    layui.use(['element', 'layedit', 'layer'], function () {
        var element = layui.element;
        layedit = layui.layedit;
        layer = layui.layer;
        buildTieEditor()
    });
    var bas;
    var ba;
    var ties;
    $.ajax({
        url: '/bas',
        async: false,
        success: function (res) {
            bas = res;
            ba = res[0];
            $.ajax({
                url: '/ties',
                data: {
                    baId: ba.baId
                },
                async: false,
                success: function (res) {
                    ties = res;
                }
            })
        }
    })
    var currentUser;
    try {
        currentUser = JSON.parse(sessionStorage.getItem('currentUser'));
    } catch (e) {
    }
    if (!currentUser) {
        currentUser = {};
    }
    vue = new Vue({
        el: '#vue-box',
        data: {
            bas: bas,
            ba: ba,
            ties: ties,
            currentUser: currentUser,
            showType: 'tie',
            floors: [],
            tie: {}
        },
        methods: {
            changeBa: function (event) {
                var index = event.target.dataset.index;
                this.$data.ba = this.$data.bas[index];
                this.$data.showType = 'tie';
                var vue = this;
                $.get('/ties', {baId: this.$data.ba.baId}, function (res) {
                    vue.$data.ties = res;
                });
                setTimeout(function () {
                    buildTieEditor();
                }, 100)
            },
            publish: function () {
                var title = $('.publish-title').val();
                var content = layedit.getContent(editIndexTie);
                var baId = this.$data.ba.baId;
                var userId = this.$data.currentUser.userId;
                var vue = this;
                if (!userId) {
                    this.loginForm();
                } else {
                    $.post('/tie', {
                        title: title,
                        content: content,
                        userId: userId,
                        baId: baId
                    }, function (res) {
                        vue.$data.ties.push(res);
                    })
                    $('.publish-form').get(0).reset();
                }
            },
            loginForm: function () {
                var vue = this;
                layer.confirm('<form class="layui-form login-form">' +
                    '<div class="layui-form-item">' +
                    '<input type="text" class="layui-input" placeholder="请输入账号" name="userId">' +
                    '</div>' +
                    '<div class="layui-form-item">' +
                    '<input type="password" class="layui-input" placeholder="请输入密码" name="password">' +
                    '</div>' +
                    '</form>', {
                    btn: ['登录', '取消'],
                    title: '登录'
                }, function (index) {
                    $.post('/user/login', $('.login-form').serialize(), function (res) {
                        if (res) {
                            vue.$data.currentUser = res;
                            sessionStorage.setItem('currentUser', JSON.stringify(res));
                        }
                    });
                    layer.close(index);
                }, function () {
                });
            },
            registerForm: function () {
                var vue = this;
                layer.confirm('<form class="layui-form register-form">' +
                    '<div class="layui-form-item">' +
                    '<input type="text" class="layui-input" placeholder="请输入用户名" name="username">' +
                    '</div>' +
                    '<div class="layui-form-item">' +
                    '<input type="password" class="layui-input" placeholder="请输入密码" name="password">' +
                    '</div>' +
                    '</form>', {
                    btn: ['注册', '取消'],
                    title: '注册'
                }, function (index) {
                    $.post('/user/register', $('.register-form').serialize(), function (res) {
                        layer.msg('登录账号为：' + res.userId);
                        vue.$data.currentUser = res;
                        sessionStorage.setItem('currentUser', JSON.stringify(res));
                    })
                    layer.close(index);
                }, function () {
                });
            },
            logout: function () {
                this.$data.currentUser = {};
                sessionStorage.removeItem('currentUser');
            },
            showFloors: function (event) {
                this.$data.showType = 'floor';
                var index = event.target.dataset.index,
                    vue = this;
                this.$data.tie = this.$data.ties[index];
                $.get('/floors', {tieId: this.$data.tie.tieId}, function (res) {
                    vue.$data.floors = res;
                })
                setTimeout(function () {
                    buildFloorEditor()
                }, 100);
            },
            reply: function () {
                var content = layedit.getContent(editIndexFloor);
                var tieId = this.$data.tie.tieId;
                var userId = this.$data.currentUser.userId;
                var vue = this;
                if (!userId) {
                    this.loginForm();
                } else {
                    $.post('/floor', {
                        content: content,
                        userId: userId,
                        tieId: tieId
                    }, function (res) {
                        vue.$data.floors.push(res);
                    })
                }
            }
        },
        filters: {
            formatDate: function (time) {
                var date = new Date(time);
                return formatDate(date, 'yyyy-MM-dd hh:mm');
            }
        },
    })
});
